package com.foot.travel.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;

import org.hybridsquad.android.library.CropHelper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;

import com.foot.travel.R;
import com.foot.travel.adapter.UpLoadImageAdapter;
import com.koalac.ironman.cache.SysAppConfig;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.ResponseProcess;
import com.koalac.ironman.net.pojo.request.PublishMyGallery;
import com.koalac.ironman.net.pojo.request.UploadImage;
import com.koalac.ironman.net.pojo.response.GalleryItem;
import com.koalac.ironman.net.pojo.response.Picture;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.net.pojo.response.User;
import com.koalac.ironman.util.BitmapUtil;
import com.koalac.ironman.util.StringUtils;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.LoadingDialog;

public class PublishPhotoActivity extends ModuleActivity {

    @ViewInject(id = R.id.root_view)
    View mRootView;
    @ViewInject(id = R.id.publish_text)
   EditText mPublishTextView;
    @ViewInject(id = R.id.publish_photo_layout)
    GridView mPublishPhotoGridView;


    UpLoadImageAdapter mUpLoadImageAdapter;
    private static final int MAX_PHOTO_NUM = 9;
    LoadingDialog mUploadImageLoadingDialog;

    private String mPhotoUrls = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setNavigationTitle("最美旅图");
	setBackButtonVisibility(true);
	mUpLoadImageAdapter = new UpLoadImageAdapter(PublishPhotoActivity.this,
		MAX_PHOTO_NUM);
	mPublishPhotoGridView.setAdapter(mUpLoadImageAdapter);
	mUploadImageLoadingDialog = LoadingDialog.createLoadingDialog(
		PublishPhotoActivity.this, "", "");
	setPublishPhotoVisibility(true);
	mPublishPhotoView.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		if (checkInput()) {
		    /**
		     * 发布纯文字
		     */
		    if (mUpLoadImageAdapter.getPhotoFilePaths().size() == 0) {
			submit(null);
			return;
		    }
		    /**
		     * 开始上传图片
		     */
		    uploadImage(0);
		}
	    }
	});
    }

    @Override
    protected void initLayout(ViewGroup rootContentView) {
	addContentView(R.layout.activity_publish_photo);
    }

    private boolean checkInput() {
	if (StringUtils.isEmpty(mPublishTextView.getText().toString())) {
	    toast("文字内容不能为空!");
	    return false;
	}
	return true;
    }


    private void uploadImage(final int index) {
	mUploadImageLoadingDialog.setDialogMessageText("正在上传第" + (index + 1)
		+ "张图片...");
	mUploadImageLoadingDialog.show();
	UploadImage uploadImage = new UploadImage();
	String filePath = mUpLoadImageAdapter.getPhotoFilePaths().get(index);
	int lastSeparatorIndex = filePath.lastIndexOf(File.separator);
	String fileName = filePath.substring(lastSeparatorIndex + 1);
	ByteArrayOutputStream outputStream = BitmapUtil.compressByCale2Stream(
		filePath, 480, 800, 200);
	MyRequest.upload(outputStream, fileName, PublishPhotoActivity.this,
		uploadImage, new ResponseProcess() {

		    @Override
		    public void onProcess(Context context, float process) {

		    }
		}, new ResponseCallback() {

		    @Override
		    public void process(boolean result, Context context,
			    Response data, String msg) {
			if (result) {
			    Picture picture = data.getObject(Picture.class);
			    mPhotoUrls += picture.getUpyunPath() + ",";
			    if (index == mUpLoadImageAdapter
				    .getPhotoFilePaths().size() - 1) {
				canceledLoadingDialog(mUploadImageLoadingDialog);
				toast("所有图片上传成功!");
				mPhotoUrls = mPhotoUrls.substring(0,
					mPhotoUrls.length() - 1);
				submit(mPhotoUrls);
				return;
			    }
			    uploadImage(index + 1);
			} else {
			    canceledLoadingDialog(mUploadImageLoadingDialog);
			    toast("所有图片上传失败!");
			}
		    }
		});
    }

    private void submit(String pictureUrls) {
	final LoadingDialog mloadingDialog = showLoadingDialog("正在发布...");
	PublishMyGallery publishMyGallery = new PublishMyGallery();
	publishMyGallery.setMessage(mPublishTextView.getText().toString());
	if (!StringUtils.isEmpty(pictureUrls)) {
	    publishMyGallery.setPictureUrl(pictureUrls);
	}
	MyRequest.request(PublishPhotoActivity.this, publishMyGallery,
		new ResponseCallback() {

		    @Override
		    public void process(boolean result, Context context,
			    Response data, String msg) {
			canceledLoadingDialog(mloadingDialog);
			if (result) {
			    User user = SysAppConfig.getInstance().getUser(
				    context);
			    GalleryItem galleryItem = data
				    .getObject(GalleryItem.class);
			    galleryItem.setHeadImgUrl(user.getHead_img_url());
			    Intent intent = new Intent();
			    galleryItem.setUserId(user.getId());
			    galleryItem.setAuthorName(user.getUser_name());
			    intent.putExtra(
				    MostBeautifulPhotoActivity.GALLRY_ITEM,
				    galleryItem);
			    setResult(RESULT_OK, intent);
			    toast("发布旅图成功!");
			    PublishPhotoActivity.this.finish();
			}
		    }
		});
    }
}
